/**
 * 
 */
package gopi.labs.bluetoothdevice;

import java.util.List;

import gopi.labs.Connector.Device;
import gopi.labs.Connector.NameValue;
import gopi.labs.datarecord.BluetoothDataRecord;
import gopi.labs.datarecord.DataRecord;
import gopi.labs.exceptions.InvalidAccessType;
import gopi.labs.exceptions.InvalidConnectionMode;
import gopi.labs.exceptions.InvalidDataRecord;

/**
 * @author GS4
 * 
 */
public class BlueToothDevice extends Device {

	private BluetoothDataRecord dataRecord;

	public enum ConnectionMode {
		MASTER, SLAVE
	}

	private ConnectionMode connectionMode;;

	public void setConnectionMode(ConnectionMode connectionMode) {
		this.connectionMode = connectionMode;
	}

	public void checkConnectionMode(ConnectionMode connectionMode)
			throws InvalidConnectionMode {
		if (connectionMode != ConnectionMode.MASTER
				&& connectionMode != ConnectionMode.SLAVE)
			throw new InvalidConnectionMode(
					connectionMode != null ? connectionMode.toString() : "");

	}

	public BlueToothDevice(String deviceId) {
		super(deviceId);

	}

	@Override
	public void defineDataRecord(DataRecord dataRecord) {
		this.dataRecord = (BluetoothDataRecord) dataRecord;

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

	}

	public void validate() throws InvalidAccessType, InvalidDataRecord,
			InvalidConnectionMode {
		super.validate();
		checkConnectionMode(this.connectionMode);
		// BT-Rule 1
		if (this.connectionMode == ConnectionMode.MASTER
				&& !passCodeCheck(this.getDeviceAttributes()))
			throw new InvalidDataRecord("Master mode requires Passcode");
		// BT-Rule 2
		if (this.getAccessType() == Device.AccessType.REQUEST
				&& this.dataRecord.getInterval() == -1)
			throw new InvalidDataRecord(
					"interval has to be defined for \"REQUEST\" Type");

	}

	private boolean passCodeCheck(List<NameValue> deviceAttributes) {

		for (int i = 0; i < deviceAttributes.size(); i++)
			if (deviceAttributes.get(i).getName().toString()
					.equalsIgnoreCase("PASSCODE")
					&& deviceAttributes.get(i).getValue() != null
					&& !deviceAttributes.get(i).getValue().toString()
							.equalsIgnoreCase(""))
				return true;
		return false;
	}

	public String toString() {
		return super.toString();
	}

}
